#include <stdio.h>
#include <string.h>

#include <arpa/inet.h>
#include <net/ethernet.h>
#include <netinet/ip.h>
#include <netinet/udp.h>

#include <unistd.h>
#include <libnet.h>

#include <pcap/pcap.h>


// ./fq1 <msg>
int main(int argc, char const *argv[])
{
    if(argc != 2) return -1;

    libnet_t *net = libnet_init(LIBNET_LINK_ADV, "ens33", NULL);

    char msg[256]="";
    int msglen=sprintf(msg, "1_lbt6_11#128#C03C59A8C0D2#0#0#0#4001#9:1:刘东海:LDH:32:%s", argv[1]);
    // udp的数据长度必须是偶数
    msglen = msglen % 2 == 0 ? msglen : msglen+1;
    printf("msglen = %d:  %s\n", msglen, msg);

    // 目标与源mac
    //uint8_t dest_mac[6] = {0x6c, 0x1f, 0xf7, 0x27, 0xc6, 0xaf};
    uint8_t dest_mac[6] = {0x4c,0xe1,0x73,0x47, 0x16, 0x3a};
    uint8_t src_mac[6] = {0xb0,0x25, 0xaa, 0x7d,0xcf, 0xaa};

    //目标与源IP
    uint32_t dest_ip = inet_addr("10.35.161.15");
    uint32_t src_ip = inet_addr("10.35.161.2");

    // 目标与源端口
    uint16_t dest_port = 2425;
    uint16_t src_port = 2425;

    // 构建udp,ipv4,mac(ethernet)
    // 传入的数据不需要 转化为网络字节序
    libnet_build_udp(src_port, dest_port, 8+msglen, 0, msg, msglen, net, 1);
    libnet_build_ipv4(20+8+msglen, 0, 500, 0, 10, 17, 0, src_ip, dest_ip, NULL,0,net,1);
    libnet_build_ethernet(dest_mac, src_mac, 0x0800, NULL,0,net, 1);

    // 发送
    libnet_write(net);

    libnet_destroy(net);
    return 0;
}
